package menupopupplugin2.popup.actions;

import java.io.File;

import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class InputPackageNamePage extends CustomWizardPage {
	private Text tfPackageName;
	private Composite container;
	private String packageName;
	private String projectPath;

	public InputPackageNamePage(String projectPath) {
		super("InputPackageNamePage");
		setTitle("Input package name page");
		setDescription("Page used for let user input root package name in "
				+ "every Spring template have.");

		this.projectPath = projectPath;
	}

	@Override
	public void createControl(Composite parent) {
		container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 2;

		// ----------------------------------------------------------

		Label lblPackageName = new Label(container, SWT.NULL);
		lblPackageName.setText("Package Name");

		tfPackageName = new Text(container, SWT.BORDER | SWT.SINGLE);
		tfPackageName.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				if (!tfPackageName.getText().isEmpty()
						&& checkRootPackageExist())
					setPageComplete(true);
				else
					setPageComplete(false);
			}
		});

		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		tfPackageName.setLayoutData(gd);

		// Required to avoid an error in the system
		setControl(container);
		setPageComplete(false);
	}

	public String getPackageName() {
		return packageName;
	}

	@Override
	public boolean isFinish() {
		return false;
	}

	@Override
	public IWizardPage getNextPage() {
		this.packageName = tfPackageName.getText();
		return super.getNextPage();
	}

	private boolean checkRootPackageExist() {
		File javaPath = new File(projectPath + "/src/main/java/"
				+ tfPackageName.getText().replace('.', '/'));
		if (javaPath.isDirectory() && javaPath.exists())
			return true;

		return false;
	}
}
